package com.haocang.szgm.ui.event.acitvity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.haocang.commonlib.network.interfaces.InitDataBeanBack;
import com.haocang.szgm.R;
import com.haocang.szgm.activity.comm.CommMediaActivity;
import com.haocang.szgm.activity.tool.CacheActivityUtil;
import com.haocang.commonlib.network.request.UploadUtil;
import com.haocang.szgm.requestcenter.DataModel;
import com.haocang.szgm.ui.event.bean.EventBean;
import com.haocang.szgm.ui.event.bean.UserDeptBean;
import com.haocang.szgm.ui.event.bean.UserTreeBean;
import com.haocang.szgm.ui.tools.activity.EnclosureListActivity;
import com.haocang.szgm.utils.bean.ProvinceBean;
import com.haocang.szgm.utils.config.Config;
import com.haocang.szgm.utils.config.WebApi;
import com.haocang.commonlib.loadingdialog.LoadingDialog;
import com.haocang.szgm.utils.tools.CacheData;
import com.haocang.szgm.utils.tools.MyTextUtils;
import com.haocang.szgm.utils.tools.OptionsItemsUtils;
import net.tsz.afinal.annotation.view.ViewInject;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class EventDetailActivity extends CommMediaActivity implements View.OnClickListener {


    @ViewInject(id = R.id.tv_02)
    TextView tv_02;
    @ViewInject(id = R.id.tv_03)
    TextView tv_03;
    @ViewInject(id = R.id.tv_04)
    TextView tv_04;
    @ViewInject(id = R.id.tv_05)
    TextView tv_05;
    @ViewInject(id = R.id.tv_06)
    TextView tv_06;
    @ViewInject(id = R.id.tv_07)
    EditText tv_07;
    @ViewInject(id = R.id.tv_08)
    TextView tv_08;
    @ViewInject(id = R.id.tv_09)
    EditText tv_09;
    @ViewInject(id = R.id.tv_10)
    TextView tv_10;
    @ViewInject(id = R.id.tv_11)
    TextView tv_11;
    @ViewInject(id = R.id.tv_12)
    TextView tv_12;
    @ViewInject(id = R.id.tv_14)
    EditText tv_14;

    @ViewInject(id = R.id.submit)
    Button submit;

    private EventBean model;
    private LoadingDialog dialog;
    private RequestQueue mQueue;
    protected double SingleTap_X = 0, SingleTap_Y = 0;


    private ArrayList<UserDeptBean> options1Items = new ArrayList<>();//一级
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();//二级

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CacheActivityUtil.addActivity(EventDetailActivity.this);

        initView();

        initEvent();

        initData();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        CacheActivityUtil.finishSingleActivity(EventDetailActivity.this);
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.activity_event_detail;
    }

    @Override
    protected boolean showNavigation() {
        return true;
    }

    @Override
    protected boolean showMedia() {
        return true;
    }

    @Override
    protected int showMoreIcon() {
        return R.drawable.icon_fujian_01;
    }

    @Override
    protected String showTitleName() {
        return "事件明细上报";
    }

    private void initView() {
        mQueue = Volley.newRequestQueue(this);
    }

    private void initEvent() {
        iv_back.setOnClickListener(this);
        iv_more.setOnClickListener(this);
        submit.setOnClickListener(this);
        tv_02.setOnClickListener(this);
        tv_03.setOnClickListener(this);
        tv_06.setOnClickListener(this);
        tv_08.setOnClickListener(this);
        tv_10.setOnClickListener(this);
        tv_11.setOnClickListener(this);
        tv_12.setOnClickListener(this);
    }

    private void initData() {

        if (!CacheData.Event_UPDATE) {
            Intent it = getIntent();
            SingleTap_X = it.getDoubleExtra("X", 0);
            SingleTap_Y = it.getDoubleExtra("Y", 0);
            iv_more.setVisibility(View.GONE);

            tv_04.setText(MyTextUtils.getNowDatatoString());
            tv_05.setText(CacheData.UserName());
        } else {
            model = CacheData.mEventBean;
            iv_more.setVisibility(View.VISIBLE);
            SingleTap_X = model.getXLng();
            SingleTap_Y = model.getYLat();

            tv_02.setText(MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetEventType(),1,model.getTypeID()));
            tv_03.setText(model.getWarningName());
            tv_04.setText(model.getCreateDT());
            tv_05.setText(model.getCreatorName());
            tv_06.setText(MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetEventLevel(),1,model.getLevel()+""));
            tv_07.setText(model.getMemo());
            tv_08.setText(MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetEventStatus(),1,model.getStatus()+""));
            tv_09.setText(model.getAlarmTime()+"");
            tv_10.setText(model.getProcessortorName());
            tv_11.setText(model.getNotifytorName());
            tv_12.setText(model.getResolveDT());
            tv_14.setText(model.getResolveMemo());

        }

        DataModel.GetApiRequestMode("UserTreeBean",WebApi.Api_List_GetUserTreeList, new InitDataBeanBack<UserTreeBean>() {
            @Override
            public void callbak(boolean b, List<UserTreeBean> list, String msg) {
                if(b){
                    ArrayList<UserDeptBean> list1 = new ArrayList<>();
                    for(UserTreeBean mm : list) {

                        UserDeptBean data1 = new UserDeptBean();
                        data1.setName(mm.getText());
                        ArrayList<String> area1 = new ArrayList<>();

                        if(mm.getChildNodes() == null)continue;
                        for(UserTreeBean.ChildNode str : mm.getChildNodes()) {
                            area1.add(str.getText());
                        }
                        data1.setCity(area1);
                        list1.add(data1);
                    }
                    options1Items = list1;
                    for (int i = 0; i < options1Items.size(); i++) {//遍历省份
                        ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
                        for (int i1 = 0; i1 < options1Items.get(i).getCity().size(); i1++) {//遍历该省份的所有城市
                            String name = options1Items.get(i).getCity().get(i1);
                            CityList.add(name);//添加城市
                        }
                        options2Items.add(CityList);
                    }
                }else{
                    ToastShow(msg);
                }
            }
        });


    }

    private void initSubmit() {


        if (SingleTap_X == 0 || SingleTap_Y == 0) {
            ToastShow("请设置坐标");
            return;
        }



        String TypeID =  MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetEventType(),0,tv_02.getText().toString());
        String Status =  MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetEventStatus(),0,tv_08.getText().toString());
        String Level = MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetEventLevel(),0,tv_06.getText().toString());
        String Processortor = MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetUserList(),0,tv_10.getText().toString());
        String Notifytor = MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetUserList(),0,tv_11.getText().toString());
        String Memo = tv_07.getText().toString();
        String ResolveDT = tv_12.getText().toString();
        String ResolveMemo = tv_14.getText().toString();
        String WarningID = MyTextUtils.GetOpitemValue(OptionsItemsUtils.GetAllReasonList(),0,tv_03.getText().toString());
        String AlarmTime =tv_09.getText().toString();

        if (MyTextUtils.IsNullByString(TypeID)) {
            ToastShow("事件类型不能为空");
            return;
        }
        if (MyTextUtils.IsNullByString(Level) ) {
            ToastShow("等级不能为空");
            return;
        }
        if (MyTextUtils.IsNullByString(Memo)) {
            ToastShow("事件描述不能为空");
            return;
        }
        if (MyTextUtils.IsNullByString(Status)) {
            ToastShow("状态不能为空");
            return;
        }
//        if (MyTextUtils.IsNullByString(Processortor)) {
//            ToastShow("处理人不能为空");
//            return;
//        }


        try {
            JSONObject maps = new JSONObject();
            if (CacheData.Event_UPDATE) {//修改
                maps.put("ID", model.getID());
            } else { //新增
                maps.put("CreateDT", MyTextUtils.getNowDatatoString());
                maps.put("Creator", CacheData.UserID());//上报人编号
            }

            maps.put("TypeID", TypeID);
            maps.put("Status", Status);
            maps.put("Level", Level);
            maps.put("Processortor", Processortor);
            maps.put("Notifytor", Notifytor);
            maps.put("Memo", Memo);
            maps.put("ResolveDT", MyTextUtils.IsNullByString(ResolveDT) ? null : ResolveDT);
            maps.put("ResolveMemo", ResolveMemo);
            maps.put("WarningID", WarningID);
            maps.put("AlarmTime", AlarmTime);
            maps.put("XLng", SingleTap_X);
            maps.put("YLat", SingleTap_Y);

            JSONObject param = new JSONObject();
            param.put("info", maps);
            param.put("filename", "Event");
            param.put("CreateUserId", CacheData.UserID());
            param.put("CreateUserName", CacheData.UserName());
            dialog = new LoadingDialog(EventDetailActivity.this, "保存中");
            dialog.show();
            UploadUtil request = new UploadUtil(
                    Config.host + WebApi.Api_ParamFileUpload,
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            dialog.close();
                            ToastShow("提交失败,请求超时！");
                            error.printStackTrace();
                        }
                    }, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject josnobject = new JSONObject(response);
                        if (josnobject.getBoolean("Result")) {

                            dialog.close();
                            ToastShow("提交成功！");
                            finish();
                            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                        } else {
                            dialog.close();
                            ToastShow("提交失败！" + josnobject.getString("Msg"));
                        }
                    } catch (JSONException e) {

                        dialog.close();
                        ToastShow("提交失败！" + e.toString());
                        e.printStackTrace();
                    }
                }

            }, "f_file[]", GetFilelist(), param);
            request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 1, 1.0f));
            mQueue.add(request);

        } catch (JSONException e1) {
            ToastShow(e1.toString());
            e1.printStackTrace();
        }
    }


    private void chooseDeviceCode(final List<ProvinceBean> items, final int pos) {
        OptionsPickerView.Builder builder = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String itemName = items.get(options1).getPickerViewText();
                switch (pos) {
                    case 2:
                        tv_02.setText(itemName);
                        break;
                    case 3:
                        tv_03.setText(itemName);
                        break;
                    case 4:
                        tv_06.setText(itemName);
                        break;
                    case 5:
                        tv_08.setText(itemName);
                        break;
                }
            }
        });
        OptionsPickerView<ProvinceBean> pickerView = new OptionsPickerView<>(builder);
        pickerView.setPicker(items);
        pickerView.show();
    }

    private void chooseTime(final int position) {
        TimePickerView.Builder builder = new TimePickerView.Builder(mContext, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
                String time = MyTextUtils.date2String(date, simpleDateFormat);
                switch (position) {
                    case 1:
                        if(!tv_04.getText().toString().equals("") && MyTextUtils.CompareStrData(tv_04.getText().toString(),time)){
                            ToastShow("解决时间不能早于发生时间！");
                            tv_12.setText("");
                        }else{
                            tv_12.setText(time);
                        }
                        break;
                }
            }
        });
        builder.setType(new boolean[]{true, true, true, true, true, false});
        TimePickerView pvTime = builder.build();
        pvTime.setDate(Calendar.getInstance());
        pvTime.show();
    }




    private void ShowPickerView(final int pos) {// 弹出地址选择器


        OptionsPickerView pvOptions = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String itemName = options2Items.get(options1).get(options2);

                switch (pos) {
                    case 6:
                        tv_10.setText(itemName);
                    case 7:
                        tv_11.setText(itemName);
                        break;
                }
            }
        }).build();//这个不能丢

        pvOptions.setPicker(options1Items, options2Items);//二级选择器（市区）
        //pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }


        @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                break;
            case R.id.iv_more:
                Intent intent = new Intent(mContext, EnclosureListActivity.class);
                intent.putExtra("BILLID", model.getID());
                startActivity(intent);
                break;
            case R.id.submit:
                initSubmit();
                break;
            case R.id.tv_02:chooseDeviceCode(OptionsItemsUtils.GetEventType(),2);  break;
            case R.id.tv_03:chooseDeviceCode(OptionsItemsUtils.GetReasonList(),3);  break;
            case R.id.tv_06:chooseDeviceCode(OptionsItemsUtils.GetEventLevel(),4);  break;
            case R.id.tv_08:chooseDeviceCode(OptionsItemsUtils.GetEventOnlyStatus(),5);  break;
            case R.id.tv_10:
                ShowPickerView(6);
                break;
            case R.id.tv_11:ShowPickerView(7);  break;
            case R.id.tv_12:chooseTime(1);  break;


        }
    }


}
